package up7.biz;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import up7.utils.JsonDateValueProcessor;
import up7.sql.SqlTable;
import up7.sql.DataBaseType;
import up7.utils.ConfigReader;
import up7.model.FileInf;
import up7.utils.PathTool;
import up7.sql.*;

public class DbFolder {

    //根节点
    JSONObject root ;//= new JObject { { "f_id", "" }, { "f_nameLoc", "根目录" }, { "f_pid", "" }, { "f_pidRoot", "" },{ "f_pathRel",""} };
    
    public static DbFolder build(){
        DataBaseType dt = ConfigReader.dbType();
        if(dt == DataBaseType.Oracle||
                dt == DataBaseType.KingBase||
                dt == DataBaseType.DMDB) return new DbFolderOracle();
        else if(dt == DataBaseType.MySQL) return new DbFolderMySQL();

        return new DbFolder();}
    
    public DbFolder() {    
    	this.root = new JSONObject();
    	this.root.put("f_id", "");
    	this.root.put("f_nameLoc", "根目录");
    	this.root.put("f_pid", "");
    	this.root.put("f_pidRoot", "");
    	this.root.put("f_pathRel", "");
    }
    
    public Map<String, JSONObject> toDic(JSONArray folders)
    {
    	Map<String, JSONObject> dt = new HashMap<String, JSONObject>();
    	for(int i = 0 , l = folders.size();i<l;++i)
        {
        	JSONObject o = folders.getJSONObject(i);
        	String id = o.getString("f_id");
        	dt.put(id, o);
        }
        return dt;
    }

    /// <summary>
    /// 构建路径
    /// </summary>
    /// <param name="fd"></param>
    /// <returns></returns>
    public JSONArray build_path(JSONObject fdCur)
    {
    	String id = fdCur.getString("id").trim();
        String pid = fdCur.getString("pid").trim();
        String pathRel = fdCur.getString("pathRel").trim();
        List<FileInf> rels = new ArrayList<FileInf>();

        //根目录
        if (pathRel=="/")
        {
            FileInf f = new FileInf();
            f.pathSvr = "/";
            f.nameLoc = "根目录";
            rels.add(f);

            FileInf dir = new FileInf();
            dir.pathRel = pathRel;
            int rpos = dir.pathRel.lastIndexOf("/");
            dir.nameLoc = dir.pathRel.substring(rpos + 1);
            rels.add(dir);
        }
        //子目录
        else {
            // /a/b/c/d/e=>,a,b,c,d,e
            int pos = 0;
            while ( (pos = pathRel.indexOf("/", pos)) !=-1)
            {
                FileInf dir = new FileInf();
                dir.pathRel = pathRel.substring(0, pos);
                dir.nameLoc = PathTool.getName(dir.pathRel);
                if (StringUtils.isEmpty(dir.nameLoc)) dir.nameLoc = "根目录";
                if (StringUtils.isEmpty(dir.pathRel)) dir.pathRel = "/";
                rels.add(dir);
                pos++;
            }
            FileInf f = new FileInf();
            f.pathRel = pathRel;
            f.nameLoc = PathTool.getName(f.pathRel);
            rels.add(f);
        }
        return JSONArray.fromObject(rels);
    }

    public FileInf read(String id) throws ParseException, IllegalAccessException, SQLException {
	    return SqlTable.build("up7_folders").readOne(FileInf.build(),
                SqlWhere.build().eq("f_id",id));
    }
    
    /**
	 * 取同名目录信息
	 * @param pathRel
	 * @param id
	 * @return
	 */
	public FileInf read(String pathRel, String id) throws ParseException, IllegalAccessException, SQLException {
	    return SqlTable.build("up7_folders").readOne(FileInf.build(),
                SqlWhere.build().eq("f_pathRel",pathRel)
        .eq("f_deleted",false)
        .ineq("f_id",id));
    }
    
	public void del(String id,String uid) throws ParseException, IllegalAccessException, SQLException {
        SqlTable.build("up7_folders").update(
                SqlSeter.build().set("f_deleted",true),
                SqlWhere.build()
                        .eq("f_id",id)
                        .eq("f_uid",uid)
        );
    }
	
    /**
	 * 检查是否存在同名目录
	 * @param name
	 * @param pid
	 * @return
	 */
	public Boolean exist_same_folder(String pathRel) 
	{
        SqlWhereMerge swm = new SqlWhereMerge();
        swm.equal("f_pathRel", pathRel);
        swm.equal("f_deleted", 0);
        String where = swm.to_sql();

        String sql = String.format("(select f_id from up7_files where %s ) union (select f_id from up7_folders where %s)", where,where);

        SqlExec se = new SqlExec();
        JSONArray fid = se.exec("up7_files", sql, "f_id", "");
        return fid.size() > 0;		
	}
	
	public static boolean existSameFolder(String name,String pid)
	{
		SqlExec se = new SqlExec();
		
		//子目录
		if(StringUtils.isEmpty(pid))
		{
			return se.count("up7_folders",new SqlParam[] {
					new SqlParam("f_nameLoc",name),
					new SqlParam("f_pid",pid),
					new SqlParam("f_deleted",false)
			})>0;
		}//根目录
		else
		{
			return se.count("up7_files",new SqlParam[] {
					new SqlParam("f_nameLoc",name),
					new SqlParam("f_pid",pid),
					new SqlParam("f_deleted",false)
			})>0;			
		}
	}	


    public static String getPathRel(String id)
    {
        SqlExec se = new SqlExec();
        JSONObject ret = se.read("up7_files", "f_pathRel", new SqlParam[] { new SqlParam("f_id", id) });
        if( !ret.has("f_pathRel") )
            ret = se.read("up7_folders", "f_pathRel", new SqlParam[] { new SqlParam("f_id", id) });
        return ret.getString("f_pathRel");
    }
    
    /**
	 * 更新子文件路径
	 * @param pathRelOld
	 * @param pathRelNew
	 */
	public void updatePathRel(String pathRelOld,String pathRelNew)
	{
        //更新子文件路径
        String sql = String.format("update up7_folders set f_pathRel=REPLACE(f_pathRel,'%s/','%s/') where CHARINDEX('%s/',f_pathRel)=1",
            pathRelOld,
            pathRelNew,
            pathRelOld
            );
        
        SqlExec se = new SqlExec();
        se.exec(sql);		
	}
	
	//批量添加
	public void addBatch(List<FileInf> arr) throws SQLException, ParseException, IllegalAccessException {
        SqlTable.build("up7_folders").inserts(arr);
	}
	
	public void complete(String id,String uid) throws ParseException, IllegalAccessException, SQLException {
        SqlTable.build("up7_folders").update(
                SqlSeter.build().set("f_complete", true),
                SqlWhere.build().eq("f_id",id)
                        .eq("f_uid",uid)
        );
    }
	
	/**
     * 加载子目录数据
     * @param uid
     * @param pid
     * @param pathRel
     */
    public String loadChildData(String uid,String pid,String pathRel) throws SQLException, InstantiationException, ParseException, IllegalAccessException {
        String pathRelSql = String.format("f_pathRel='%s'+f_nameLoc",pathRel);
        if(ConfigReader.dbType() != DataBaseType.SqlServer)
            pathRelSql = String.format("f_pathRel=CONCAT('%s',f_nameLoc)",pathRel);

        //加载文件列表
        List<FileInf> files = SqlTable.build("up7_files").reads(FileInf.build(),
                "f_id,f_pid,f_nameLoc,f_sizeLoc,f_lenLoc,f_time,f_pidRoot,f_fdTask,f_pathSvr,f_pathRel",
                SqlWhere.build().
                        eq("f_uid",uid).eq("f_complete",true)
                        .eq("f_deleted",false)
                        .eq("f_fdChild",true)
                        .sql("f_pathRel",pathRelSql),
                SqlSort.build().desc("f_fdTask").desc("f_time")
        );

        //加载子目录
        List<FileInf> folders = SqlTable.build("up7_folders").reads(FileInf.build(),
                "f_id,f_nameLoc,f_pid,f_sizeLoc,f_time,f_pidRoot,f_pathRel",
                SqlWhere.build().
                        eq("f_uid",uid)
                        .eq("f_complete",true)
                        .eq("f_deleted",false)
                        .sql("f_pathRel",pathRelSql),
                SqlSort.build().desc("f_time")
        );

        for (FileInf f : folders)
        {
            f.fdTask=true;
            f.fdChild=false;
            files.add(0,f);
        }

        JSONObject o = new JSONObject();
        o.put("count", files.size());
        o.put("code", 0);
        o.put("msg", "");
        o.put("data", JSONArray.fromObject(files.toArray(), JsonDateValueProcessor.build()));

        return o.toString();
    }

    /**
     * 加载根目录数据
     * @param uid
     * @param pid
     * @param pathRel
     */
    public String loadRootData(String uid,String pid,String pathRel) throws SQLException, InstantiationException, ParseException, IllegalAccessException {
        List<FileInf> files = SqlTable.build("up7_files").reads(FileInf.build(),
                "f_id,f_pid,f_nameLoc,f_sizeLoc,f_lenLoc,f_time,f_pidRoot,f_fdTask,f_pathSvr,f_pathRel,f_object_key",
                SqlWhere.build()
                        .eq("f_uid",uid)
                        .eq("f_complete",true)
                        .eq("f_deleted",false)
                        .eq("f_fdChild",false),
                SqlSort.build().desc("f_fdTask").desc("f_time")
        );

        JSONObject o = new JSONObject();
        o.put("count", files.size());
        o.put("code", 0);
        o.put("msg", "");
        o.put("data", JSONArray.fromObject(files.toArray(), JsonDateValueProcessor.build()));

        return o.toString();
    }
	
	public void add(FileInf dir) throws ParseException, IllegalAccessException, SQLException {
        SqlTable.build("up7_folders").insert(dir);
    }
}
